package com.xyc.gulimall.member.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyc.common.utils.HttpUtils;
import com.xyc.common.utils.PageUtils;
import com.xyc.common.utils.Query;
import com.xyc.gulimall.member.dao.MemberDao;
import com.xyc.gulimall.member.dao.MemberLevelDao;
import com.xyc.gulimall.member.entity.MemberEntity;
import com.xyc.gulimall.member.entity.MemberLevelEntity;
import com.xyc.gulimall.member.exception.PhoneExistException;
import com.xyc.gulimall.member.exception.UsernameExistException;
import com.xyc.gulimall.member.service.MemberService;
import com.xyc.gulimall.member.vo.MemberLoginVo;
import com.xyc.gulimall.member.vo.MemberRegisterVo;
import com.xyc.gulimall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberRegisterVo memberRegisterVo) {
        MemberEntity memberEntity = new MemberEntity();

        //设置默认等级
        MemberLevelEntity memberLevelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(memberLevelEntity.getId());

        //检查用户名和手机号是否唯一。为了让controller感知异常，使用异常机制
        checkPhoneUnique(memberRegisterVo.getPhone());
        checkUsername(memberRegisterVo.getUsername());

        //设置用户名和手机号
        memberEntity.setMobile(memberRegisterVo.getPhone());
        memberEntity.setUsername(memberRegisterVo.getUsername());
        memberEntity.setNickname(memberRegisterVo.getUsername());
        //设置密码，加密 可逆/不可逆    MD5不可逆
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(memberRegisterVo.getPassword());
        memberEntity.setPassword(encode);

        //其它默认信息

        //保存
        MemberDao memberDao = this.baseMapper;
        memberDao.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        Long mobile = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUsername(String username) throws UsernameExistException {
        Long mobile = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (mobile > 0) {
            throw new UsernameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo memberLoginVo) {

        String loginAccount = memberLoginVo.getLoginAccount();
        String password = memberLoginVo.getPassword();

        //1、去数据库查询
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>()
                .eq("username", loginAccount)
                .or()
                .eq("mobile", loginAccount));
        if (memberEntity == null) {
            //数据库无此用户，登录失败
            return null;
        } else {
            //1、获取到数据库的password_db
            String password_db = memberEntity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            //2、进行密码匹配
            boolean matches = passwordEncoder.matches(password, password_db);
            if (matches) {
                //登录成功
                return memberEntity;
            } else {
                return null;
            }
        }
    }

    /**
     * gitee授权登录
     *
     * @param socialUser
     * @return
     * @throws Exception
     */
    @Override
    public MemberEntity login(SocialUser socialUser) {
        System.out.println("社交用户：" + socialUser);
        JSONObject jsonObject = null;
        try {
            //1、查询当前社交用户的社交账号信息（uid、昵称、性别等）
            Map<String, String> querys = new HashMap<>();
            querys.put("access_token", socialUser.getAccess_token());
            HttpResponse response = HttpUtils.doGet(
                    "https://gitee.com",
                    "/api/v5/user",
                    "get",
                    new HashMap<>(),
                    querys
            );

            if (response.getStatusLine().getStatusCode() == 200) {
                //查询成功
                String json = EntityUtils.toString(response.getEntity());
                System.out.println("授权用户信息：" + json);
                jsonObject = JSON.parseObject(json);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("查询gitte用户失败" + e.getMessage());
            return null;
        }

        //登录和注册合并逻辑
        //社交id
        String uid = null;
        if (jsonObject != null) {
            uid = jsonObject.getString("id");
        }
        //1、判断当前社交用户是否已经登录过系统
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity != null) {
            //该用户已经注册了
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(socialUser.getExpires_in());

            memberDao.updateById(update);

            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());
            return memberEntity;
        } else {
            //2、没有查到当前社交用户对应的记录就注册一个用户
            MemberEntity register = new MemberEntity();
            //昵称
            String name = jsonObject.getString("name");
            //用户名
            String email = jsonObject.getString("email");

            register.setSocialUid(uid);
            register.setNickname(name);
            register.setEmail(email);

            register.setAccessToken(socialUser.getAccess_token());
            register.setExpiresIn(socialUser.getExpires_in());
            memberDao.insert(register);

            return register;
        }
    }

    /**
     * 微博授权登录
     *
     * @param socialUser
     * @return
     * @throws Exception
     */
//    @Override
//    public MemberEntity login(SocialUser socialUser) {
//        System.out.println("社交用户：" + socialUser);
//        //登录和注册合并逻辑
//        String uid = socialUser.getUid();
//        //1、判断当前社交用户是否已经登录过系统
//        MemberDao memberDao = this.baseMapper;
//        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
//        if (memberEntity != null) {
//            //该用户已经注册了
//            MemberEntity update = new MemberEntity();
//            update.setId(memberEntity.getId());
//            update.setAccessToken(socialUser.getAccess_token());
//            update.setExpiresIn(socialUser.getExpires_in());
//
//            memberDao.updateById(update);
//
//            memberEntity.setAccessToken(socialUser.getAccess_token());
//            memberEntity.setExpiresIn(socialUser.getExpires_in());
//            return memberEntity;
//        } else {
//            //2、没有查到当前社交用户对应的记录就注册一个用户
//            MemberEntity register = new MemberEntity();
//            try {
//                //3、查询当前社交用户的社交账号信息（昵称、性别等）
//                Map<String, String> querys = new HashMap<>();
//                querys.put("access_token", socialUser.getAccess_token());
//                HttpResponse response = HttpUtils.doGet(
//                        "https://gitee.com",
//                        "/api/v5/user",
//                        "get",
//                        new HashMap<>(),
//                        querys
//                );
//
//                if (response.getStatusLine().getStatusCode() == 200) {
//                    //查询成功
//                    String json = EntityUtils.toString(response.getEntity());
//                    System.out.println("授权用户信息：" + json);
//                    JSONObject jsonObject = JSON.parseObject(json);
//                    //社交id
//                    String id = jsonObject.getString("id");
//                    //昵称
//                    String name = jsonObject.getString("name");
//                    //用户名
//                    String email = jsonObject.getString("email");
//
//                    register.setSocialUid(id);
//                    register.setNickname(name);
//                    register.setEmail(email);
//
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            register.setAccessToken(socialUser.getAccess_token());
//            register.setExpiresIn(socialUser.getExpires_in());
//            memberDao.insert(register);
//
//            return register;
//        }
//    }
}